<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :immediate-check="false"
    >
      <comment-item v-for="(item, index) in list" :key="index" :item="item"></comment-item>
    </van-list>
    <!-- 评论列表 -->

    <!-- 发布评论 -->
    <van-cell-group class="publish-wrap">
      <van-field clearable placeholder="请输入评论内容">
        <van-button slot="button" size="mini" type="info">发布</van-button>
      </van-field>
    </van-cell-group>
    <!-- /发布评论 -->
  </div>
</template>

<script>
import { getComments } from '@/api/comment.js'
import commentItem from './comment-item.vue'
// import eventBus from '@/utils/eventBus.js'
export default {
  components: { commentItem },
  name: 'ArticleComment',
  props: {
    source: [String, Number],
    type: {
      type: String,
      default: 'a'
    }
  },
  data () {
    return {
      list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      offset: undefined
    }
  },
  created () {
    this.onLoad()
    // eventBus.$on('onPostSucces', data => {
    //   this.list.unshift(data)
    // })
  },
  methods: {
    // 当出现到页面和触底会触发
    async onLoad () {
      // 1.发请求
      const { data: { data: { last_id: offset, results, total_count: total } } } = await getComments({
        type: this.type,
        source: this.source,
        offset: this.offset,
        limit: 10
      })
      // 2.追加数据
      this.offset = offset
      this.list.push(...results)
      this.$emit('set-total', total)
      // 3.改变状态值
      this.loading = false
      // 4.判断是否结束
      if (results.length === 0) {
        this.finished = true
      }
    }
  }
}
</script>

<style scoped lang="less">
  .publish-wrap {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
  }

  .van-list {
    margin-bottom: 45px;
  }
</style>
